package edu.hawaii.duedates;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * A class for the University of Hawaii Library System.
 * 
 * @author Arthur Shum and Erin Kim.
 */
public class UhLibrary implements Library {

  /** The URL to log in to the University of Hawaii Library System. */
  private static final String url = 
    "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";

  /** The patron's UH ID number. Used to log in to the University of Hawaii Library System. */
  private final String uhId;

  /** The patron's last name. Used to log in to the University of Hawaii Library System. */
  private final String lastName;

  /**
   * Constructs a UhLibrary object, given a UH ID and a last name.
   * 
   * @param uhId The patron's UH ID number.
   * @param lastName The patron's last name.
   */
  public UhLibrary(String uhId, String lastName) {
    this.uhId = uhId;
    this.lastName = lastName;
  }

  /**
   * Attempts to log in to the University of Hawaii Library System.
   * 
   * @return The WebConversation instance after successful login.
   * @throws Exception If an error occurs while logging in.
   */
  public WebConversation login() throws Exception {
    // UH Library website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");
    form.setParameter("BC", this.uhId);
    form.setParameter("LN", this.lastName);
    form.submit();
    response = conversation.getCurrentPage();
    if (response.getText().contains("Sorry, Login unsuccessful")) {
      throw new Exception("Error while logging in to UH Library");
    }
    return conversation;
  }

  /**
   * Retrieves information about items checked out from the University of Hawaii Library System by
   * the logged-in patron. The information is stored in a table where the text of cell 0,0 is
   * "Renew?".
   * 
   * @return A ready-to-print string containing info about checked-out items.
   * @throws Exception If an error occurs while retrieving info.
   */
  public String getInfo() throws Exception {
    try {
      WebConversation conversation = this.login();
      WebResponse response = conversation.getCurrentPage();
      WebTable table = response.getTableStartingWith("Renew?");
      // If the table containing the information doesn't exist.
      if (table == null) {
        return "\nNo items checked out from the University of Hawaii Library System.\n\n";
      }
      else {
        return formatInfo(table);
      }
    }
    catch (Exception e) {
      throw new Exception("Error getting UH Book info", e);
    }
  }

  /**
   * Formats information stored in a table into a ready-to-print string. In the table, each row is
   * for a separate item; column 1 is for the item itself; column 2 is for the item type; and column
   * 3 is for the status.
   * 
   * @param table The WebTable containing checked-out item info.
   * @return A ready-to-print string containing info about checked-out items.
   */
  private String formatInfo(WebTable table) {
    String items = "\nResults for the University of Hawaii Library System:\n\n";
    for (int i = 1; i < table.getRowCount(); i++) {
      String item = table.getCellAsText(i, 1);
      String type = table.getCellAsText(i, 2);
      String status = table.getCellAsText(i, 3);
      items = items.concat("Item  :  " + item + "\n");
      items = items.concat("Type  :  " + type + "\n");
      items = items.concat("Status:  " + status + "\n\n");
    }
    return items;
  }

}
